﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using CoreEx.Database.Client;
using LinFu.IoC.Interfaces;
using LinFu.IoC.Configuration;
using LinFu.IoC;
using System.Data;

namespace CoreEx.Database.Client.Implementation
{
    [Factory(typeof(IDbConnection))]
    public class ConnectionFactory : IFactory<IDbConnection>
    {
        #region IFactory Members

        public IDbConnection CreateInstance(IFactoryRequest request)
        {
            //Get the connection info that corresponds to the service name;
            var connectionInfo = request.Container.GetService<IConnectionInfo>(request.ServiceName);

            //Get the DbProviderFactory that corresponds to the provider name;
            var dbProviderFactory = request.Container.GetService<DbProviderFactory>(request.ServiceName);

            //Create the connection
            var connection = dbProviderFactory.CreateConnection();
            
            connection.ConnectionString = connectionInfo.ConnectionString;

            var connectionProxy = request.Container.GetService<IProxyFactory<IDbConnection>>().CreateProxy(connection);
            ((IDbConnectionInfo)connectionProxy).Name = connectionInfo.Name;
            ((IDbConnectionInfo) connectionProxy).ProviderName = connectionInfo.ProviderName;
            return connectionProxy;
        }

        #endregion
    }
}